package com.dc.wifi.main.utils;

import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.dc.wifi.main.DCApplication;

import java.util.concurrent.TimeUnit;

public class SoundPlayer222 {

    private static final String TAG = "SoundPlayer";
    private MediaPlayer mediaPlayer;
    private Handler handler;
    private long intervalMillis;

    public SoundPlayer222() {
        handler = new Handler(Looper.getMainLooper());
    }

    /**
     * 初始化MediaPlayer并设置播放资源。
     *
     * @param resId 资源ID，指向一个音频文件。
     */
    public void init(int resId) {
        mediaPlayer = MediaPlayer.create(DCApplication.getInstance(), resId);
        if (mediaPlayer == null) {
            Log.e(TAG, "Failed to create MediaPlayer");
        }
    }

    /**
     * 设置播放频率（1到10次/秒）。
     *
     * @param frequency 播放频率（1-10）。
     */
    public void setFrequency(int frequency) {
        if (frequency < 1 || frequency > 10) {
            throw new IllegalArgumentException("Frequency must be between 1 and 10");
        }
        intervalMillis = TimeUnit.SECONDS.toMillis(1) / frequency;
    }

    /**
     * 开始播放滴滴声。
     */
    public void startPlaying() {
        if (mediaPlayer == null || mediaPlayer.isPlaying()) {
            return;
        }
        mediaPlayer.start();
        handler.postDelayed(playAgain, intervalMillis);
    }

    /**
     * 停止播放滴滴声。
     */
    public void stopPlaying() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            handler.removeCallbacks(playAgain);
            mediaPlayer.reset();
        }
    }

    /**
     * MediaPlayer播放完毕后调用的方法，用于循环播放。
     */
    private Runnable playAgain = new Runnable() {
        @Override
        public void run() {
            if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                handler.postDelayed(this, intervalMillis);
            }
        }
    };

    /**
     * 释放MediaPlayer资源。
     */
    public void release() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}